package org.seedltd.upms.service.impl.sys;

import org.seedltd.core.base.BasePage;
import org.seedltd.core.base.BaseServiceImpl;
import org.seedltd.core.mybatis.conditions.ProUpdate;
import org.seedltd.upms.mapper.sys.SysDictTypeMapper;
import org.seedltd.upms.model.sys.entity.SysDictType;
import org.seedltd.upms.model.sys.form.SysDictTypeForm;
import org.seedltd.upms.model.sys.form.SysDictTypeSearchForm;
import org.seedltd.upms.model.sys.vo.SysDictTypeVO;
import org.seedltd.upms.service.sys.SysDictService;
import org.seedltd.upms.service.sys.SysDictTypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import lombok.AllArgsConstructor;

/**
 * 字典类型业务实现
 * 
 * @author laizuan
 * @since 2021/09/01
 */
@Service
@AllArgsConstructor
public class SysDictTypeServiceImpl extends BaseServiceImpl<SysDictTypeMapper, SysDictType>
    implements SysDictTypeService {

    private final SysDictService sysDictService;

    @Override
    public SysDictTypeVO findById(Long id) {
        return q().selectById(id, SysDictTypeVO.class);
    }

    @Override
    public Long add(SysDictTypeForm form) {
        return u().save(form, new SysDictType()).getId();
    }

    @Override
    public boolean update(SysDictTypeForm form) {
        ProUpdate.Cb<SysDictType> cb = new ProUpdate.Cb<>() {
            @Override
            public boolean before(SysDictType pojo) {
                if (!pojo.getEnabled().equals(form.getEnabled())) {
                    sysDictService.clearCache(pojo.getDictType());
                }
                return true;
            }
        };
        return u(cb).updateById(form, form.getId());
    }

    @Override
    @Transactional
    public boolean delete(Long id) {
        SysDictType pojo = baseMapper.selectById(id);
        if (pojo == null) {
            return true;
        }
        sysDictService.delete(pojo.getDictType(), null);
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    public BasePage<SysDictTypeVO> page(SysDictTypeSearchForm searchForm) {
        return q(searchForm).selectPage(searchForm.getStart(), searchForm.getSize(), SysDictTypeVO.class);
    }
}